package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.modular.dao.CommonMapper;
import com.drd.dt.modular.dao.OrderMapper;
import com.drd.dt.modular.dao.UserMapper;
import com.drd.dt.modular.dto.GoodsDetailDTO;
import com.drd.dt.modular.entity.Order;
import com.drd.dt.modular.entity.User;
import com.drd.dt.modular.service.JDService;
import com.drd.dt.properties.JDLMPropertyConfig;
import com.drd.dt.util.*;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import jd.union.open.goods.promotiongoodsinfo.query.request.UnionOpenGoodsPromotiongoodsinfoQueryRequest;
import jd.union.open.goods.promotiongoodsinfo.query.response.PromotionGoodsResp;
import jd.union.open.goods.promotiongoodsinfo.query.response.UnionOpenGoodsPromotiongoodsinfoQueryResponse;
import jd.union.open.order.query.request.OrderReq;
import jd.union.open.order.query.request.UnionOpenOrderQueryRequest;
import jd.union.open.order.query.response.UnionOpenOrderQueryResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 86514 on 2019/3/21.
 */

@Transactional
@Service
public class JDServiceImpl implements JDService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JDLMPropertyConfig jdlmPropertyConfig;
    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private GoldCoinServiceImpl goldCoinService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMoneyServiceImpl testMoneyService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FilterGoodsUtil filterGoodsUtil;
    @Autowired
    private FilterGoodsUtil goodsUtil;


    /**
     * 获取最新订单
     */
    @Override
    public Tip task() throws Exception {
        logger.info("【黑桃省钱开始同步京东最新订单...】");
        String jd_url = "http://img1.360buyimg.com/da/";
        Long end_date = System.currentTimeMillis() / 1000;
        Long start_date = end_date - 3600 * 24 * 1;//一天的数据
        Integer page = 1;
        String jd_app_key = jdlmPropertyConfig.getKpl_appKey();
        String jd_app_secret = jdlmPropertyConfig.getKpl_appSecret();

        Boolean hasMore = false;
        SimpleDateFormat y_m_d_h_m_s = Constant.y_M_d_H_m_s;
        String our_time = "2019-12-03 18:00:00";//这之前的订单不进库
        do {
            String resultStr = getOrderList(start_date, end_date, 0, page, jd_app_key, jd_app_secret);
            if (!StringUtils.isEmpty(resultStr)) {
                JSONObject resultObj = JSON.parseObject(resultStr);
                JSONObject jd_kepler_order_getlist_response = resultObj.getJSONObject("jd_kepler_order_getlist_response");
                hasMore = jd_kepler_order_getlist_response.getBoolean("hasMore");
                JSONArray orders = jd_kepler_order_getlist_response.getJSONArray("orders");//获取订单

                for (Object arr : orders) {//循环订单
                    JSONObject order = (JSONObject) arr;
                    Integer status = order.getInteger("status");
                    Integer yn = order.getInteger("yn");//订单是否有效；0表示无效，1表示有效
                    if (status != 5) {//已经付款
                        continue;
                    }
                    if (yn == 0) {
                        continue;
                    }
                    JSONArray skuInfos = order.getJSONArray("skuInfos");
                    Order createOrder = new Order();
                    Double price = order.getDouble("totalPrice");
                    String order_id = order.getString("orderId");
                    String createDate = order.getString("createDate");
                    Integer user_id = order.getInteger("keplerCustomerInfo");
                    if (StringUtils.isEmpty(user_id)){
                        continue;
                    }
                    createOrder.setOrder_id(order_id);
                    createOrder.setStatus(order.getInteger("status") == 5 ? 2 : 3);
                    String product_name = "";
                    String product_pic_url = "";
                    if (skuInfos.size() > 0) {
                        product_name = skuInfos.getJSONObject(0).getString("name");
                        product_pic_url = jd_url + skuInfos.getJSONObject(0).getString("imgUrl");
                    }
                    createOrder.setProduct_name(product_name);
                    createOrder.setProduct_pic_url(product_pic_url);
                    createOrder.setType(2);
                    createOrder.setActual_amount(String.valueOf(price));
                    createOrder.setUser_id(user_id);
                    String reg = "(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})";
                    createDate = createDate.replaceAll(reg, "$1-$2-$3 $4:$5:$6");

                    if (y_m_d_h_m_s.parse(createDate).getTime() < y_m_d_h_m_s.parse(our_time).getTime()) {
                        continue;
                    }

                    createOrder.setCreate_time(createDate);
                    Integer num = 0;
                    StringBuilder goods_id = new StringBuilder();
                    for (Object s : skuInfos) {//商品循环
                        JSONObject skuInfo = (JSONObject) s;
                        goods_id.append("<" + skuInfo.getString("id") + ">");
                        Integer number = skuInfo.getInteger("num");
                        num = num + number;
                    }
                    createOrder.setNumber(num);
                    createOrder.setProduct_id(goods_id.toString());
                    createOrder.setUser_rake_back("0");
                    if (price > 0) {
                        //查找订单
                        Order repeatOrder = orderMapper.getRepeatOrder(order_id);
                        if (null == repeatOrder) {
                            //使用红包
                            Integer redpacket = goldCoinService.userRedpacket(String.valueOf(user_id));
                            createOrder.setRedpacket(redpacket);
                            orderMapper.insert(createOrder);
                        }
                    }
                }
                page++;
            }
        } while (hasMore);

        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 同步完成订单
     */
    @Override
    public Tip successOrder(String beginTime, String type) throws Exception {
        logger.info("【黑桃省钱开始同步京东完成订单...】：" + beginTime + "时间");
        if (StringUtils.isEmpty(type)) {
            type = "1";
        }
        String resultStr = getJDOrderListByUnion(beginTime, Integer.valueOf(type));
        logger.info("resultStr:【" + resultStr + "】");
        if (!StringUtils.isEmpty(resultStr)) {
            JSONObject endOrderList = JSON.parseObject(resultStr);
            if (endOrderList.getInteger("code") != 200) {
                return ResultUtil.result(801, endOrderList.getString("message"));
            }
            JSONArray orderInfos = endOrderList.getJSONArray("data");
            if (null != orderInfos) {
                for (Object orderInfo : orderInfos) {//订单循环
                    JSONObject orders = (JSONObject) orderInfo;
                    String order_id = orders.getString("orderId");
                    Integer validCode = orders.getInteger("validCode");
                    JSONArray skuLists = orders.getJSONArray("skuList");
                    Double rake_back = 0.0;
                    Double estimateCosPrice = 0.0;
                    StringBuilder goods_id = new StringBuilder();
                    for (Object skuList : skuLists) {//商品循环
                        JSONObject skuListDetail = (JSONObject) skuList;
                        rake_back = rake_back + skuListDetail.getDouble("estimateFee");
                        goods_id.append("<" + skuListDetail.getString("skuId") + ">");
                        estimateCosPrice = estimateCosPrice + skuListDetail.getDouble("estimateCosPrice");
                    }
                    if (estimateCosPrice > 0) {
                        Map map = new HashMap();
                        map.put("order_id", order_id);
                        map.put("actual_amount", estimateCosPrice);//实际付款

                        if (validCode == 17) {//已经完成 （提前支付）
//                        if (validCode == 18) {//已经结算
                            String clear_time = "";
                            if (validCode == 17 && skuLists.size() > 0) {//已经完成 （提前支付）
//                            if (validCode == 18 && skuLists.size() > 0) {//已结算
                                clear_time = skuLists.getJSONObject(0).getString("payMonth");//该字段为预估 不建议使用
                                if(clear_time == "" || clear_time.equals("0")){
                                    DateFormat d = new SimpleDateFormat("yyyyMMddHHmmss");
                                    clear_time = d.format(new Date()); //当前时间作为结算时间
                                }
                            }
                            map.put("clear_time", clear_time);
                            map.put("rake_back", rake_back);
                            logger.info("【黑桃省钱开始返佣金...订单号" + order_id + "的佣金为【" + rake_back + "】元】");
//                            goodsUtil.rakeMoneyNew(order_id, rake_back, goods_id.toString(), clear_time, 0.0);//返佣金
                        } else if (validCode < 16) {//无效订单
                            map.put("status", "4");
                            //修改失效订单返佣

                            Order RepeatOrder = orderMapper.getRepeatOrder(order_id);
                            orderMapper.updateOrder(map);
                            if (null != RepeatOrder && RepeatOrder.getStatus() != 4) {//如果订单是第一次无效
                                RepeatOrder.setStatus(4);
                                testMoneyService.updateOrderFansRake(RepeatOrder);
                            }

                        } else {
                            Order RepeatOrder = orderMapper.getRepeatOrder(order_id);
                            String rakeBack = RepeatOrder.getRake_back();
                            if (StringUtils.isEmpty(rakeBack) || Double.parseDouble(rakeBack) == 0) {//如果订单是第一次更新
                                RepeatOrder.setRake_back(String.valueOf(rake_back));
                                User user = userMapper.selectById(RepeatOrder.getUser_id());
                                Double rate = testMoneyService.getRakeBackRatebyUser(user);
                                String yugu = testMoneyService.round(String.valueOf(rate * rake_back));
                                RepeatOrder.setUser_rake_back_yugu(yugu);
                                map.put("rake_back", rake_back);
                                map.put("user_rake_back_yugu", yugu);
                                map.put("buytype", "0");
                                map.put("user_rake", rate);
                                orderMapper.updateOrder(map);

                                RepeatOrder.setRake_back(String.valueOf(rake_back));
                                testMoneyService.updateOrderFansRake(RepeatOrder);
                            }

                        }
                    }
                }
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 通过京东联盟获取订单数据
     *
     * @param time
     * @return
     * @throws Exception
     */
    public String getJDOrderListByUnion(String time, Integer type) throws Exception {
        String url = jdlmPropertyConfig.getUrl();
        String appKey = jdlmPropertyConfig.getJdlm_appKey();
        String appSecret = jdlmPropertyConfig.getJdlm_appSecret();
        String accessToken = "";

        JdClient client = new DefaultJdClient(url, accessToken, appKey, appSecret);
        UnionOpenOrderQueryRequest unionOpenOrderQueryRequest = new UnionOpenOrderQueryRequest();
        Integer page = 1;
        Integer pageSize = 200;
        OrderReq orderReq = new OrderReq();
        orderReq.setPageNo(page);
        orderReq.setPageSize(pageSize);
        orderReq.setType(type);
        orderReq.setTime(time);
        unionOpenOrderQueryRequest.setOrderReq(orderReq);
        UnionOpenOrderQueryResponse response = client.execute(unionOpenOrderQueryRequest);
        return JSON.toJSONString(response);
    }

    /**
     * 获取最新订单
     *
     * @return bool|string
     */
    public String getOrderList(Long beginTime, Long endTime, Integer orderId, Integer page, String app_key, String app_secret) throws Exception {
        JSONObject param = new JSONObject();
        String jd_url = jdlmPropertyConfig.getUrl();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
        String bTime = sd.format(new Date(beginTime * 1000));
        String eTime = sd.format(new Date(endTime * 1000));
        Map map = new HashMap();
        param.put("pageIndex", page);
        param.put("pageSize", 20);
        param.put("beginTime", bTime);
        param.put("endTime", eTime);
        if (orderId != 0) {
            param.put("orderId", orderId);
        }
        String v = "2.0";
        String method = "jd.kepler.order.getlist";
        String sign_method = "md5.0";
        String format = "json";
        String timestamp = sdf.format(new Date());
        map.put("v", v);
        map.put("method", method);
        map.put("app_key", app_key);
        map.put("sign_method", sign_method);
        map.put("format", format);
        map.put("param_json", param);
        map.put("timestamp", timestamp);
        String sign = StringUtil.sortByMapKey(map, app_secret);
        String entity = ("v=" + v + "&method=" + method + "&app_key=" + app_key + "&sign_method=" + sign_method + "&format=" +
                format + "&param_json=" + param + "&timestamp=" + timestamp + "&sign=" + sign);
        String resultStr = HttpConnectionPoolUtil.postCommandFromNet2(jd_url, entity);
        return resultStr;
    }

    public String getJDDetailGet(String sku) throws Exception {
        String appKey = "";
        String jdAccessToken = "";
        Map config = commonMapper.getConfigInfo();
        if (null != config.get("jd_app_key")) {
            appKey = (String) config.get("jd_app_key");
        }
        if (null != config.get("jd_app_secret")) {
            jdAccessToken = (String) config.get("jd_app_secret");
        }
        JSONObject paramJson = new JSONObject();
        paramJson.put("sku", sku);
        String time = Constant.y_M_d_H_m_s.format(new Date());
        String body = "method=" + jdlmPropertyConfig.getDetailUrl() + "&app_key=" + appKey +
                "&access_token=" + jdAccessToken + "&timestamp=" + MD5Utils.MD5Encode(MD5Utils.MD5Encode(time, "UTF-8"), "UTF-8") + "&format=json&v=1.0"
                + "&param_json=" + paramJson.toString();
        String url = jdlmPropertyConfig.getUrl() + "?" + body;
        String data = HttpConnectionPoolUtil.getJD(url);
        return data;
    }


    @Override
    public Tip getJDDetail(String sku, Integer user_id,HttpServletRequest request, String deviceT, String app_version) throws Exception {
//        String data = getJDDetailGet(sku);
        String data = getJDDetailGetJDLM(sku);
        GoodsDetailDTO detailDTO = new GoodsDetailDTO();
        if (!StringUtils.isEmpty(deviceT) && Integer.valueOf(deviceT) == 1) {//ios过审版
            detailDTO = filterGoodsUtil.filterIOSVersion(detailDTO, request, app_version);
        }
        Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
        if (!StringUtils.isEmpty(data)) {
            JSONObject detail = JSON.parseObject(data);

            String goodsName = detail.containsKey("goodsName") && detail.getString("goodsName") != null ? detail.getString("goodsName") : "";
            String goodsId = detail.containsKey("skuId") && detail.getString("skuId") != null ? detail.getString("skuId") : "";
            String price = detail.containsKey("unitPrice") && detail.getString("unitPrice") != null ? detail.getString("unitPrice") : "";
            String goodsMainPicture = detail.containsKey("imgUrl") && detail.getString("imgUrl") != null ? detail.getString("imgUrl") : "";
            String storeURL = detail.containsKey("shopUrl") && detail.getString("shopUrl") != null ? detail.getString("shopUrl") : "";
            String shopName = detail.containsKey("shopName") && detail.getString("shopName") != null ? detail.getString("shopName") : "";
            String storeUserId = detail.containsKey("shopId") && detail.getString("shopId") != null ? detail.getString("shopId") : "";
            String storeIcon = detail.containsKey("shopLogo") && detail.getString("shopLogo") != null ? detail.getString("shopLogo") : "";
            Double commisionRatioWl = detail.containsKey("commisionRatioWl") && detail.getDouble("commisionRatioWl") != null ? detail.getDouble("commisionRatioWl") : 0.0;

            //佣金比例
            Double commission = Double.valueOf(price) * (commisionRatioWl / 100) * reback_money.doubleValue();//用户返佣
            Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
            Double upcommission = Double.valueOf(price) * (commisionRatioWl / 100) * upreback_money.doubleValue();//上级返佣
            String vipDesc = filterGoodsUtil.vipDesc(upcommission,user_id);
            detailDTO.setVipDesc(vipDesc);
            detailDTO.setCommission(String.format("%.2f", commission));
            detailDTO.setUpcommission(String.format("%.2f", upcommission));
            detailDTO.setType(2);
            detailDTO.setGoodsName(goodsName);
            detailDTO.setGoodsId(goodsId);
            detailDTO.setPrice(price);
            detailDTO.setGoodsMainPicture(goodsMainPicture);
            if (detail.containsKey("images")) {
                JSONArray imgs = detail.getJSONArray("images");
                List<String> detailList = new ArrayList();
                imgs.stream().forEach(t -> detailList.add("http://img12.360buyimg.com/N1/" + String.valueOf(t)));
                detailDTO.setGoodsCarouselPictures(detailList);
            }
            detailDTO.setStoreURL(storeURL);
            detailDTO.setStoreName(shopName);
            detailDTO.setStoreUserId(storeUserId);
            detailDTO.setStoreIcon(storeIcon);
//            detailDTO.setSales((int) (1000 + Math.random() * 50000) + "");


            //h5
            String h5URL = "https://in.m.jd.com/product/jieshao/" + sku + ".html";
            detailDTO.setH5Url(h5URL);
            //店铺信息
            Map<String, Object> storeGiveAMark = new HashMap<String, Object>();
            storeGiveAMark.put("storeName", detailDTO.getStoreName());
            storeGiveAMark.put("storeUserId", detailDTO.getStoreUserId());
            storeGiveAMark.put("storeIcon", detailDTO.getStoreIcon());
            storeGiveAMark.put("storeURL", detailDTO.getStoreURL());
            detailDTO.setStoreGiveAMark(storeGiveAMark);

            //相关 商品  根据相关目录查询
//            String categoryName = detail.containsKey("categoryName") && detail.getString("categoryName") != null ? detail.getString("categoryName") : "";
//            Tip tip = getJdBrokerageList(sku, "1", "0", user_id);
            detailDTO.setRelatedRecommendation(new ArrayList<>());

        }


        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), detailDTO);

    }

    /**
     * 京东捜券
     *
     * @throws Exception
     */
    @Override
    public Tip getJdBrokerageList(String keywords, String page, String sort, Integer user_id) throws Exception {
        List<GoodsDetailDTO> response = new ArrayList<>();
        keywords = StringUtil.getKeyword(keywords);
        if (StringUtils.isEmpty(page)) {page = "1";}
        if (StringUtils.isEmpty(sort)) {sort = "0";}
        if (!StringUtils.isEmpty(keywords)) {
            if (keywords.equals("全部")) {
                keywords = "百货";
            }
        }
        //请求地址
        JSONObject queryParam = new JSONObject();
        JSONObject pageParam = new JSONObject();
        String appKey = "";
        String jdAccessToken = "";
        String appSecret = "";
        Integer pageSize = Constant.PAGE_SIZE_20;
        Map config = commonMapper.getConfigInfo();
        if (null != config.get("jd_app_key")) {
            appKey = (String) config.get("jd_app_key");
        }
        if (null != config.get("jd_access_token")) {
            jdAccessToken = (String) config.get("jd_access_token");
        }
        if (null != config.get("jd_app_secret")) {
            appSecret = (String) config.get("jd_app_secret");
        }
        String time = Constant.y_M_d_H_m_s.format(new Date());
        queryParam.put("keywords", keywords);
        pageParam.put("pageNum", page);
        pageParam.put("pageSize", pageSize);
        Map map = new HashMap();
        map.put("method", jdlmPropertyConfig.getSearchgoods());
        map.put("app_key", appKey);
        map.put("access_token", jdAccessToken);
        map.put("timestamp", time);
        map.put("format", "json");
        map.put("v", "1.0");
        map.put("sign_method", "md5");
        JSONObject param_json = new JSONObject();
        param_json.put("queryParam", queryParam);
        param_json.put("pageParam", pageParam);
        param_json.put("orderField", sort);
        map.put("param_json", param_json);
        String sign = StringUtil.sortByMapKey(map, appSecret);
        String body = "method=" + jdlmPropertyConfig.getSearchgoods() + "&app_key=" + appKey +
                "&access_token=" + jdAccessToken + "&timestamp=" + time + "&format=json&v=1.0&sign_method=md5&sign=" + sign
                + "&param_json=" + param_json.toString();
        String url = jdlmPropertyConfig.getUrl() + "?" + body;
        String data = HttpConnectionPoolUtil.getJD(url);
        if (null != data && !data.equals("")) {
            JSONObject object = JSON.parseObject(data).getJSONObject("jd_kpl_open_xuanpin_searchgoods_response");
            if (object.getString("code").equals("0")) {
                JSONObject result = object.getJSONObject("result");
                JSONArray queryVo = result.getJSONArray("queryVo");
                Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
                if (null != queryVo && queryVo.size() > 0) {
                    queryVo.stream().forEach(t -> {
                        JSONObject detail = (JSONObject) t;
                        String price = detail.getString("price");
                        GoodsDetailDTO detailDTO = new GoodsDetailDTO();
                        detailDTO.setType(2);
                        detailDTO.setGoodsId(detail.getString("skuId"));
                        String goodsName = detail.getString("wareName");
                        detailDTO.setGoodsName(goodsName);
                        detailDTO.setGoodsMainPicture("http://img12.360buyimg.com/N1/" + detail.getString("imageUrl"));
                        detailDTO.setPrice(price);
                        detailDTO.setPriceAfterCoupon(price);
//                        detailDTO.setSales(detail.getString("qtty_30"));
                        //佣金比例
                        Double commisionRatioWl = 0.0;
                        if (detail.containsKey("commisionRatioWl")) {
                            commisionRatioWl = Double.valueOf(detail.getString("commisionRatioWl"));
                        }
                        if (commisionRatioWl != 0) {
                            detailDTO.setIfCoupon(true);
                            Double commission = Double.valueOf(price) * (commisionRatioWl / 100) * reback_money.doubleValue();//用户返佣
                            Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                            Double upcommission = Double.valueOf(price) * (commisionRatioWl / 100) * upreback_money.doubleValue();//上级返佣
                            detailDTO.setCommission(String.format("%.2f", commission));
                            detailDTO.setUpcommission(String.format("%.2f", upcommission));
                        }
                        response.add(detailDTO);
                    });
                }
                return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), response);
            } else {
                return ResultUtil.result(801, object.getString("message"));
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    private String getJDDetailGetJDLM(String sku) throws Exception {
        /************************京东联盟****************************/
        JdClient client = new DefaultJdClient(jdlmPropertyConfig.getUrl(), "", jdlmPropertyConfig.getJdlm_appKey(), jdlmPropertyConfig.getJdlm_appSecret());
        UnionOpenGoodsPromotiongoodsinfoQueryRequest request = new UnionOpenGoodsPromotiongoodsinfoQueryRequest();
        request.setSkuIds(sku);
        UnionOpenGoodsPromotiongoodsinfoQueryResponse response = client.execute(request);
        PromotionGoodsResp[] resps = response.getData();
        if (resps.length > 0) {
            return JSON.toJSONString(resps[0]);
        }
        return "";
    }


    @Override
    public List<String> getJDOrderTime(String time) {
       return orderMapper.getJDOrderTime(time);
    }
}
